<html>
<head>
<script src="ajax.js" ></script>
<script src="janusvideoroom.json" ></script>
<script src="janusvideoroom.js" ></script>
<script src="ag-grid.min.js"></script>
</head>
<body> 
	Janus Url:<input id="janusUrl" type="text" size="50" /> 
	Room id:<input id="janusRoom" type="number" />
	<div id="myGrid" style="height: 80%;" class="ag-fresh"></div>
</body>
<script>
	// set default value
	document.querySelector('#janusUrl').value  = janusRoomConfig.url;
	document.querySelector('#janusRoom').value = janusRoomConfig.roomId;

	var janus;	
	
	// columns
	var columnDefs = [
	    { headerName: "Url"    , field: "url"    },
	    { headerName: "Status" , field: "status", cellRenderer: function(params) { return '<b>' + params.value.toUpperCase() + '</b>'; } },
	    { headerName: "RoomId" , field: "roomid" },
	    { headerName: "Action" , 
	      field: "action", 
	      cellRenderer: function(params) { 
	        var eDiv = document.createElement('div');
		eDiv.innerHTML = '<button class="btn-simple">'+params.value+'</button>';
		var eButton = eDiv.querySelectorAll('.btn-simple')[0];
		eButton.addEventListener('click', function() {
			if (params.value === "join") {
				params.data.roomid = document.querySelector('#janusRoom').value;
				params.api.refreshCells([params.node], ['roomid']);
				
				if (!janus) {
					janus = new JanusVideoRoom(document.querySelector('#janusUrl').value, clientCallBack, null, send);
				}
				janus.join(parseInt(params.data.roomid), params.data.url, params.data.url);
				
			} else {
				janus.leave(parseInt(params.data.roomid), params.data.url, params.data.url);
			}
		});

		return eDiv;
              } 
	    }
	];

	// options
	var gridOptions = {
		enableFilter: true,
		enableSorting: true,
		enableColResize: true,
		columnDefs: columnDefs,
		rowHeight: 30,
		onGridReady: function($event) { $event.api.sizeColumnsToFit(); }
	};
	
	// fill grid
	var grid = new agGrid.Grid(document.querySelector('#myGrid'), gridOptions);	

	function clientCallBack(name, status) {		
		var updatedNodes = [];
		gridOptions.api.forEachNode( function(node) {
			var data = node.data;
			if (data.url === name) {
			    data.status = status;
			    if (status === "up") {
				data.action = "leave";
			    } else if (status === "down") {
				data.roomid = "";
				data.action = "join";
			    }
			    updatedNodes.push(node);
			}
		});
		gridOptions.api.refreshCells(updatedNodes, ['status','action','roomid']);
	}
	
	// ------------------------------------------
	// init device list 
	// ------------------------------------------	
	function onGetDeviceList(remoteDeviceList) {
	
		var rowData = [];
		remoteDeviceList.forEach(function(item) {
			rowData.push({url: item , status:"down", action:"join" })
		});

		gridOptions.api.addItems(rowData);
	}
	
	// load
	window.onload         = function() { 
		send("/getVideoDeviceList", null, null, onGetDeviceList); 
	} 
</script>
</html>

